package com.dangdi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@ServerEndpoint("/sokect")
public class websokectHandler {
    @Autowired
    private static int countPer = 0;
    private Session session;
    public static int cun = 0;
    private static List<websokectHandler> webSokects = new ArrayList<websokectHandler>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSokects.add(this);
        addCountPer();
    }

    @OnError
    public void onError(Session session, Throwable error) {
        removeCountPer();
    }

    @OnClose
    public void onClose() {
        webSokects.remove(this);
        removeCountPer();
    }

    @OnMessage
    public void onMessage(String message) {
        for (websokectHandler webSoekct : webSokects) {
            try {
                webSoekct.getSession().getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void addCountPer() {
        websokectHandler.countPer++;
    }

    public void removeCountPer() {
        websokectHandler.countPer--;
    }

    public int getCountPer() {
        return countPer;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public static void setCountPer(int countPer) {
        websokectHandler.countPer = countPer;
    }
}
